/**
* @Author: fiyc
* @Date : 2019-04-19 15:54
* @FileName : mqtt-client.js
* @Description :
*     - MQTT客户端类
*/
const mqtt = require('mqtt');
const uuid = require('uuid');


Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

class Client {

    /**
     * 
     * @param {Object} config 配置参数 
     * @param {String} config.host MQTT连接地址
     * @param {Number} config.port MQTT连接端口
     * @param {String} config.username MQTT用户名
     * @param {String} config.password MQTT密码
     * @param {String} config.id 客户端ID
     * @param {boolean} config.clean 客户端ID
     * @param {Function} onConnectCallback 连接成功时回调
     */
    constructor(config, onConnectCallback) {
        let { host, port, username, password, clean, id } = config;
        this.host = host || "127.0.0.1";
        this.port = port || 1883;
        this.username = username || "";
        this.password = password || "";
        this.id = id || uuid.v4().toString();
        this.clean = clean == null || clean == undefined ? true : clean;
        this.onConnectCallback = onConnectCallback;


        let url = `mqtt://${this.host}:${this.port}`;
        console.log('------------------------------ 开始建立MQTT连接 -----------------------------');
        console.log(`[连接地址] ${url}`);
        console.log(`[客户端ID] ${this.id}`);
        console.log(`[用户名] ${this.username}`);
        console.log(`[密码] ${this.password}`);
        console.log(`[清除会话] ${this.clean}`);


        let options = { clean: this.clean, clientId: this.id };
        if (this.username && this.password) {
            options.username = this.username;
            options.password = this.password;
        }

        this.client = mqtt.connect(url, options);
        this.client.on('message', this.onMessage);
        this.client.on('error', this.onError);
        this.client.on('connect', () => {
            console.log('------------------------------ 连接建立成功 -----------------------------');
            if (typeof this.onConnectCallback === 'function') {
                this.onConnectCallback(this.client);
            }
        });
    }

    onMessage(topic, message) {
        console.log('');
        console.log(`[${new Date().Format('yyyy-MM-dd hh:mm:ss')}] 收到一条消息`);
        console.log(`[主题] ${topic}`);
        console.log(`[内容] ${message.toString()}`);
        console.log('');
    }

    onError(error) {
        console.error(`连接出现异常: ${error}`);
    }

    destory() {
    }
}

module.exports = Client;